package com.attrisoft.sanger.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mailer {

    public static void send(String to, String subject, File log, File times) {
        String text = "";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(times));
            for (String line; (line = reader.readLine()) != null;) 
                text += line + "\n";
            reader.close();
            text += "\n";
            reader = new BufferedReader(new FileReader(log));
            for (String line; (line = reader.readLine()) != null;) 
                text += line + "\n";
            reader.close();
        } catch (Exception e) {
            text = e.getMessage();
        }
        send(to, subject, text);
    }
    
    public static void send(String to, String subject, String text) {
        Properties config = new Properties();
        config.put("mail.smtp.host", System.getProperty("mail.smtp.host"));
        Session session = Session.getDefaultInstance(config, null);
        MimeMessage message = new MimeMessage(session);
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setText(text);
            message.setFrom(new InternetAddress("sanger-demo@no.such.domain"));
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
